package com.situ.company.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FmtRequest {
	
	private FmtRequest(){
		
	}
	
	/**
	 * 属性名与参数名不一致时
	 * @param <T>
	 * @param req
	 * @param clazz
	 * @param fields
	 * 			key=属性名 value=参数名
	 */
	public static <T> T parseModel(HttpServletRequest req,Class<T> clazz,Map<String,String> fields) {
		T obj = null;
		try {
			obj = clazz.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		for (Entry<String, String> entry : fields.entrySet()) {
			try {
				Field field = clazz.getDeclaredField(entry.getKey());
				field.setAccessible(true);
				field.set(obj, req.getParameter(entry.getValue()));
			} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return obj;
	}
	
	/**
	 * 属性名与参数名一致时，可以试用该方法进行实例化
	 * @param <T>
	 * @param req
	 * @param clazz
	 * @return
	 */
	public static <T> T parseModel(HttpServletRequest req,Class<T> clazz) {
		T obj = null;
		try {
			obj = clazz.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		Map<String, String[]> map = req.getParameterMap();
		for (Entry<String, String[]> entry : map.entrySet()) {
			String name = entry.getKey();
			if("action".equals(name))
				continue;
			try {
				Field field = clazz.getDeclaredField(name);
				field.setAccessible(true);
				field.set(obj, entry.getValue()[0]);
			} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return obj;
	}
	
	public static void out(HttpServletResponse resp,String result) throws IOException {
		PrintWriter out = resp.getWriter();
		out.append(result);
		out.flush();
		out.close();
		out = null;
	}
}
